
// src/pages/Storage/Storage.tsx
import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Progress,
  Tabs,
  message,
  Modal,
  Form,
  Input,
  InputNumber,
} from 'antd';
import type { TableColumnsType } from 'antd';
import {
  PlusOutlined,
  FolderOutlined,
  FileOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { apiClient } from '../../api/client';

interface StoragePool {
  name: string;
  uuid: string;
  state: string;
  capacity: number;
  allocation: number;
  available: number;
  type: string;
}

interface StorageVolume {
  name: string;
  path: string;
  type: string;
  capacity: number;
  allocation: number;
}

const Storage: React.FC = () => {
  const [pools, setPools] = useState<StoragePool[]>([]);
  const [volumes, setVolumes] = useState<StorageVolume[]>([]);
  const [selectedPool, setSelectedPool] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchPools();
  }, []);

  useEffect(() => {
    if (selectedPool) {
      fetchVolumes(selectedPool);
    }
  }, [selectedPool]);

  const fetchPools = async () => {
    setLoading(true);
    try {
      const { data } = await apiClient.get('/storage/pools');
      setPools(data);
      if (data.length > 0 && !selectedPool) {
        setSelectedPool(data[0].name);
      }
    } catch (error) {
      message.error('获取存储池列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchVolumes = async (poolName: string) => {
    try {
      const { data } = await apiClient.get(`/storage/pools/${poolName}/volumes`);
      setVolumes(data);
    } catch (error) {
      message.error('获取卷列表失败');
    }
  };

  const handleCreateVolume = async (values: any) => {
    if (!selectedPool) return;

    try {
      await apiClient.post(`/storage/pools/${selectedPool}/volumes`, values);
      message.success('卷创建成功');
      setModalVisible(false);
      form.resetFields();
      fetchVolumes(selectedPool);
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleDeleteVolume = (volumeName: string) => {
    if (!selectedPool) return;

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除卷 "${volumeName}" 吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await apiClient.delete(
            `/storage/pools/${selectedPool}/volumes/${volumeName}`
          );
          message.success('卷已删除');
          fetchVolumes(selectedPool);
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const poolColumns: TableColumnsType<StoragePool> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <Space>
          <FolderOutlined />
          {name}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (state: string) => (
        <Tag color={state === 'active' ? 'success' : 'default'}>{state}</Tag>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '使用率',
      key: 'usage',
      render: (_, record) => {
        const percent = (record.allocation / record.capacity) * 100;
        return (
          <div style={{ width: '200px' }}>
            <Progress percent={Math.round(percent)} size="small" />
            <div style={{ fontSize: '12px', color: '#666' }}>
              {(record.allocation / 1024 / 1024 / 1024).toFixed(2)} GB /{' '}
              {(record.capacity / 1024 / 1024 / 1024).toFixed(2)} GB
            </div>
          </div>
        );
      },
    },
  ];

  const volumeColumns: TableColumnsType<StorageVolume> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <Space>
          <FileOutlined />
          {name}
        </Space>
      ),
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '容量',
      dataIndex: 'capacity',
      key: 'capacity',
      render: (capacity: number) =>
        `${(capacity / 1024 / 1024 / 1024).toFixed(2)} GB`,
    },
    {
      title: '分配',
      dataIndex: 'allocation',
      key: 'allocation',
      render: (allocation: number) =>
        `${(allocation / 1024 / 1024 / 1024).toFixed(2)} GB`,
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDeleteVolume(record.name)}
        >
          删除
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Card title="存储管理">
        <Tabs
          activeKey={selectedPool || undefined}
          onChange={setSelectedPool}
          tabBarExtraContent={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setModalVisible(true)}
              disabled={!selectedPool}
            >
              创建卷
            </Button>
          }
          items={pools.map((pool) => ({
            key: pool.name,
            label: pool.name,
          }))}
        />

        {selectedPool && (
          <>
            <div style={{ marginBottom: '16px' }}>
              <Table
                columns={poolColumns}
                dataSource={pools.filter((p) => p.name === selectedPool)}
                rowKey="uuid"
                pagination={false}
              />
            </div>

            <Card title="卷列表" size="small">
              <Table
                columns={volumeColumns}
                dataSource={volumes}
                rowKey="path"
                loading={loading}
              />
            </Card>
          </>
        )}
      </Card>

      <Modal
        title="创建存储卷"
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} layout="vertical" onFinish={handleCreateVolume}>
          <Form.Item
            label="卷名称"
            name="name"
            rules={[{ required: true, message: '请输入卷名称' }]}
          >
            <Input placeholder="例如: disk01.qcow2" />
          </Form.Item>

          <Form.Item
            label="容量 (GB)"
            name="capacity"
            rules={[{ required: true, message: '请输入容量' }]}
          >
            <InputNumber min={1} max={1000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label="格式" name="format" initialValue="qcow2">
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Storage;